#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals

import json
from calibre.ebooks.BeautifulSoup import Tag
from calibre.web.feeds.news import BasicNewsRecipe


def classes(classes):
    q = frozenset(classes.split(' '))
    return dict(attrs={
        'class': lambda x: x and frozenset(x.split()).intersection(q)})


class NatGeo(BasicNewsRecipe):
    title = u'National Geographic'
    description = 'Daily news articles from The National Geographic'
    language = 'en'
    oldest_article = 20
    max_articles_per_feed = 25
    encoding = 'utf8'
    publisher = 'nationalgeographic.com'
    category = 'science, nat geo'
    __author__ = 'Kovid Goyal'
    masthead_url = 'http://s.ngeo.com/wpf/sites/themes/global/i/presentation/ng_logo_small.png'
    description = 'Inspiring people to care about the planet since 1888'
    timefmt = ' [%a, %d %b, %Y]'
    no_stylesheets = True
    use_embedded_content = False
    remove_attributes = ['style']
    remove_javascript = False

    keep_only_tags = [
            classes('mainArt byline'),
            dict(id='article__body'),
    ]
    remove_tags = [
            classes('hide-from-mobile ad-holder enlarge-button'),
            dict(name='svg meta'.split()),
    ]

    feeds = [
        (u'Daily News', u'http://feeds.nationalgeographic.com/ng/News/News_Main')
    ]

    def parse_feeds(self):
        feeds = BasicNewsRecipe.parse_feeds(self)
        for feed in feeds:
            for article in feed.articles[:]:
                if 'Presented' in article.title or 'Pictures' in article.title:
                    feed.articles.remove(article)
        return feeds

    def preprocess_html(self, soup):
        for div in soup.findAll(attrs={'data-pestle-module': 'PictureFill'}):
            script = div.find('script')
            src = json.loads(self.tag_to_string(script))['src']
            div.name = 'img'
            div['src'] = src

        for div in soup.findAll(attrs={'data-src': True, 'class': 'delayed-image-load'}):
            url = div['data-src']
            idx = url.find('.jpg/{width')
            if idx != -1:
                url = url[:idx + 4]
                img = Tag(soup, "img")
                img['src'] = url
                div.append(img)

        for script in soup.findAll('script'):
            script.extract()
        return soup
